package cn.virens.web.components.open.wxma;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.stereotype.Component;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.config.WxMaConfig;

@Component
public class WxMaServiceImpl extends cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl {
	private final static ThreadLocal<String> CONFIG_STORAGE_CHOSE = new ThreadLocal<String>();

	private final Map<String, WxMaConfig> configStorageMap = new ConcurrentHashMap<>();

	public void addConfigStorage(WxMaConfig configStorage) {
		this.configStorageMap.put(configStorage.getAppid(), configStorage);
	}

	public void removeConfigStorage(String mpId) {
		this.configStorageMap.remove(mpId);
	}

	@Override
	public WxMaConfig getWxMaConfig() {
		if (configStorageMap.size() == 1) {
			return configStorageMap.values().iterator().next();
		} else {
			return configStorageMap.get(CONFIG_STORAGE_CHOSE.get());
		}
	}

	public String getAppid() {
		return CONFIG_STORAGE_CHOSE.get();
	}

	public boolean switchover(String appid) {
		if (configStorageMap.containsKey(appid)) {
			CONFIG_STORAGE_CHOSE.set(appid);
		} else {
			return false;
		}

		return true;
	}

	public WxMaService switchoverTo(String appid) {
		if (configStorageMap.containsKey(appid)) {
			CONFIG_STORAGE_CHOSE.set(appid);

			return this;
		}

		throw new RuntimeException(String.format("无法找到对应【%s】的公众号配置信息，请核实！", appid));
	}

}
